<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>我来给你画个饼 保障你醒来就能赚到钱</title>
    <style>
        body {
            margin: 0;
            padding: 0;
            overflow: hidden;
            touch-action: none;
            display: flex;
            flex-direction: column;
            align-items: center;
            height: 100vh;
            width: 100vw;
            font-family: 'Arial', sans-serif;
            background-color: #f5f5f5;
        }
        #app-container {
            width: 100%;
            max-width: 500px;
            height: 100%;
            display: flex;
            flex-direction: column;
            position: relative;
            background-color: white;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
        }
        #header {
            padding: 10px;
            text-align: center;
            background-color: #4285f4;
            color: white;
            font-weight: bold;
            font-size: 18px;
            border-bottom: 1px solid #3367d6;
        }
        #canvas-container {
            position: relative;
            width: 100%;
            flex: 0 0 auto;
            overflow: hidden;
            border-bottom: 1px solid #e0e0e0;
        }
        #canvas {
            position: absolute;
            top: 0;
            left: 0;
            touch-action: none;
        }
        #users-online {
            width: 100%;
            padding: 10px 0;
            background-color: white;
            border-bottom: 1px solid #e0e0e0;
            overflow-x: auto;
            white-space: nowrap;
            -webkit-overflow-scrolling: touch;
        }
        #users-list {
            display: flex;
            list-style: none;
            padding: 0 10px;
            margin: 0;
        }
        .user-item {
            display: inline-flex;
            flex-direction: column;
            align-items: center;
            margin-right: 15px;
        }
        .user-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background-color: #ddd;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-bottom: 5px;
            position: relative;
        }
        .user-avatar.online::after {
            content: '';
            position: absolute;
            bottom: 0;
            right: 0;
            width: 10px;
            height: 10px;
            background-color: #0f0;
            border-radius: 50%;
            border: 2px solid white;
        }
        .user-name {
            font-size: 12px;
            max-width: 60px;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        #activity-log {
            flex: 1;
            overflow-y: auto;
            padding: 10px;
            background-color: #f9f9f9;
            border-bottom: 1px solid #e0e0e0;
        }
        .log-item {
            padding: 8px;
            margin-bottom: 8px;
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            font-size: 14px;
        }
        .log-item .time {
            color: #888;
            font-size: 12px;
            margin-top: 4px;
        }
        .log-item .user {
            font-weight: bold;
        }
        #controls {
            position: relative;
            bottom: 0;
            left: 0;
            right: 0;
            z-index: 10;
            padding: 10px;
            background-color: white;
            border-top: 1px solid #e0e0e0;
            display: flex;
            flex-direction: column;
            gap: 10px;
            transition: height 0.3s ease;
            user-select: none;
            max-height: 60vh;
            overflow-y: auto;
        }
        #controls.expanded {
            height: auto;
        }
        #controls.collapsed {
            height: 50px;
            overflow: hidden;
        }
        #toggle-controls {
            width: 100%;
            text-align: center;
            padding: 5px;
            background: #f0f0f0;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            user-select: none;
            margin-bottom: 10px;
        }
        .color-palette {
            display: flex;
            flex-wrap: wrap;
            gap: 5px;
            margin: 5px 0;
        }
        .color-option {
            width: 25px;
            height: 25px;
            border-radius: 50%;
            border: 1px solid #ccc;
            cursor: pointer;
        }
        .color-option.active {
            border: 2px solid #000;
        }
        button {
            padding: 8px 10px;
            background: #4285f4;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            margin: 2px 0;
        }
        button:hover {
            background: #3367d6;
        }
        .control-group {
            margin: 5px 0;
            display: flex;
            flex-direction: column;
            width: 100%;
        }
        .control-group label {
            margin-bottom: 5px;
            font-weight: bold;
        }
        /* 用户光标样式 */
        .user-cursor {
            position: absolute;
            width: 20px;
            height: 20px;
            border-radius: 50%;
            border: 2px solid #000;
            transform: translate(-50%, -50%);
            pointer-events: none;
            z-index: 5;
            transition: left 0.1s ease, top 0.1s ease;
        }
        .user-cursor::after {
            content: attr(data-user);
            position: absolute;
            top: -20px;
            left: 50%;
            transform: translateX(-50%);
            background-color: rgba(0, 0, 0, 0.7);
            color: white;
            padding: 2px 5px;
            border-radius: 3px;
            font-size: 12px;
            white-space: nowrap;
        }
        select, input[type="range"] {
            width: 100%;
            padding: 8px;
            border-radius: 5px;
            border: 1px solid #ccc;
            background-color: white;
        }
        input[type="color"] {
            width: 100%;
            height: 40px;
            border-radius: 5px;
            border: 1px solid #ccc;
        }
    </style>
</head>
<body>
    <div id="app-container">
        <div id="header">协作绘画</div>
        <div id="canvas-container">
            <canvas id="canvas"></canvas>
        </div>
        <div id="users-online">
            <ul id="users-list"></ul>
        </div>
        <div id="activity-log"></div>
        <div id="controls" class="collapsed">
            <button id="toggle-controls">展开工具栏</button>
            <div class="control-group">
                <label for="color">画笔颜色：</label>
                <input type="color" id="color" value="#000000">
                <div class="color-palette" id="colorPalette"></div>
            </div>
            <div class="control-group">
                <label for="size">画笔大小：</label>
                <input type="range" id="size" value="5" min="1" max="50">
                <span id="sizeValue">5</span>
            </div>
            <div class="control-group">
                <label for="blend-mode">混合模式：</label>
                <select id="blend-mode">
                    <option value="source-over">正常</option>
                    <option value="multiply">正片叠底</option>
                    <option value="screen">滤色</option>
                    <option value="overlay">叠加</option>
                    <option value="darken">变暗</option>
                    <option value="lighten">变亮</option>
                    <option value="color-dodge">颜色减淡</option>
                    <option value="color-burn">颜色加深</option>
                    <option value="hard-light">强光</option>
                    <option value="soft-light">柔光</option>
                    <option value="difference">差值</option>
                    <option value="exclusion">排除</option>
                    <option value="hue">色相</option>
                    <option value="saturation">饱和度</option>
                    <option value="color">颜色</option>
                    <option value="luminosity">亮度</option>
                </select>
            </div>
            <div class="control-group">
                <label for="background">背景颜色：</label>
                <input type="color" id="background" value="#ffffff">
            </div>
            <div class="control-group">
                <button id="clear">清空画布</button>
            </div>
            <div class="control-group">
                <button id="undo">撤销</button>
            </div>
            <div class="control-group">
                <button id="redo">重做</button>
            </div>
        </div>
    </div>
    <script>
        // 生成唯一的用户ID
        const userId = 'user_' + Math.random().toString(36).substr(2, 9);
        // 用户名（可以让用户自定义，这里使用随机名称）
        const userName = '用户' + Math.floor(Math.random() * 1000);
        
        // 存储其他用户的光标元素
        const userCursors = {};
        // 存储在线用户列表
        const onlineUsers = {};
        
        // 从localStorage加载历史记录
        let history = [];
        let currentStep = -1;
        
        // 从localStorage加载背景颜色
        const savedBackground = localStorage.getItem('drawBackground');
        if (savedBackground) {
            document.body.style.backgroundColor = savedBackground;
            document.getElementById('background').value = savedBackground;
        }

        // 保存历史记录到localStorage
        function saveHistoryToStorage() {
            try {
                // 不直接保存ImageData对象，而是保存画布的base64编码
                const tempHistoryData = [];
                for (let i = 0; i < history.length; i++) {
                    const tempCanvas = document.createElement('canvas');
                    tempCanvas.width = el.width;
                    tempCanvas.height = el.height;
                    const tempCtx = tempCanvas.getContext('2d');
                    tempCtx.putImageData(history[i], 0, 0);
                    tempHistoryData.push(tempCanvas.toDataURL('image/png', 0.5)); // 使用压缩率0.5减小数据量
                }
                localStorage.setItem('drawHistory', JSON.stringify(tempHistoryData));
            } catch (e) {
                console.error('保存历史记录失败:', e);
                // 如果存储失败（可能是因为数据太大），清空历史记录
                localStorage.removeItem('drawHistory');
            }
        }

        // 从localStorage加载历史记录
        function loadHistoryFromStorage() {
            try {
                const savedHistory = JSON.parse(localStorage.getItem('drawHistory'));
                if (savedHistory && Array.isArray(savedHistory)) {
                    // 限制最大历史记录数量，防止内存溢出
                    const maxHistoryLength = 10;
                    const historyToLoad = savedHistory.slice(-maxHistoryLength);
                    
                    // 异步加载历史记录
                    let loadedCount = 0;
                    historyToLoad.forEach((dataUrl, index) => {
                        const img = new Image();
                        img.onload = function() {
                            const tempCanvas = document.createElement('canvas');
                            tempCanvas.width = el.width;
                            tempCanvas.height = el.height;
                            const tempCtx = tempCanvas.getContext('2d');
                            tempCtx.drawImage(img, 0, 0, el.width, el.height);
                            history[index] = tempCtx.getImageData(0, 0, el.width, el.height);
                            
                            loadedCount++;
                            if (loadedCount === historyToLoad.length) {
                                currentStep = history.length - 1;
                                // 加载最后一步到画布
                                if (currentStep >= 0) {
                                    ctx.putImageData(history[currentStep], 0, 0);
                                }
                            }
                        };
                        img.src = dataUrl;
                    });
                }
            } catch (e) {
                console.error('加载历史记录失败:', e);
                history = [];
                currentStep = -1;
                localStorage.removeItem('drawHistory');
            }
        }

        // 保存背景颜色到localStorage
        function saveBackgroundToStorage(color) {
            localStorage.setItem('drawBackground', color);
        }

        // 控制面板折叠功能
        document.getElementById('toggle-controls').addEventListener('click', function() {
            const controls = document.getElementById('controls');
            controls.classList.toggle('expanded');
            this.textContent = controls.classList.contains('expanded') ? '工具栏 ▼' : '工具栏 ▲';
        });

        // 常用颜色列表
        const commonColors = [
            '#000000', '#FFFFFF', '#FF0000', '#00FF00', '#0000FF', 
            '#FFFF00', '#FF00FF', '#00FFFF', '#FFA500', '#800080',
            '#008000', '#800000', '#808000', '#008080', '#C0C0C0'
        ];

        // 初始化颜色选择面板
        const colorPalette = document.getElementById('colorPalette');
        commonColors.forEach(color => {
            const colorOption = document.createElement('div');
            colorOption.className = 'color-option';
            colorOption.style.backgroundColor = color;
            colorOption.dataset.color = color;
            colorOption.addEventListener('click', function() {
                document.getElementById('color').value = color;
                ctx.strokeStyle = color;
                updateActiveColor(color);
                sendOperation({type: 'setColor', color: color});
            });
            colorPalette.appendChild(colorOption);
        });

        function updateActiveColor(color) {
            document.querySelectorAll('.color-option').forEach(option => {
                option.classList.remove('active');
                if (option.dataset.color === color) {
                    option.classList.add('active');
                }
            });
        }

        // 初始化画布
        var el = document.getElementById('canvas');
        const CANVAS_WIDTH = 400;
        const CANVAS_HEIGHT = 400;
        el.width = CANVAS_WIDTH;
        el.height = CANVAS_HEIGHT;
        var ctx = el.getContext('2d');
        ctx.lineCap = 'round';
        ctx.lineJoin = 'round';

        // 创建一个离屏画布用于存储所有用户的绘画
        const sharedCanvas = document.createElement('canvas');
        sharedCanvas.width = CANVAS_WIDTH;
        sharedCanvas.height = CANVAS_HEIGHT;
        const sharedCtx = sharedCanvas.getContext('2d');
        sharedCtx.lineCap = 'round';
        sharedCtx.lineJoin = 'round';

        // 初始化状态变量
        var isDrawing = false;
        var lastX = 0;
        var lastY = 0;

        // 活动日志
        const activityLog = [];
        const MAX_LOG_ITEMS = 50;

        // 初始化画笔颜色、大小和混合模式
        ctx.strokeStyle = '#000';
        ctx.lineWidth = 5;
        ctx.globalCompositeOperation = 'source-over'; // 默认混合模式
        updateActiveColor('#000000');

        // 加载历史记录
        loadHistoryFromStorage();

        // 调整画布容器大小
        function adjustCanvasContainer() {
            const container = document.getElementById('canvas-container');
            const containerWidth = container.clientWidth;
            
            // 设置画布高度为宽度相同，创建正方形画布
            container.style.height = containerWidth + 'px';
        }

        // 页面加载时调整画布容器大小
        adjustCanvasContainer();

        // 切换控制面板显示状态
        document.getElementById('toggle-controls').addEventListener('click', function() {
            const controls = document.getElementById('controls');
            controls.classList.toggle('collapsed');
            this.textContent = controls.classList.contains('collapsed') ? '展开工具栏' : '收起工具栏';
        });

        // 添加活动日志
        function addActivityLog(userId, userName, action) {
            const now = new Date();
            const timeString = now.getHours().toString().padStart(2, '0') + ':' + 
                              now.getMinutes().toString().padStart(2, '0');
            
            const logItem = {
                userId: userId,
                userName: userName,
                action: action,
                time: timeString
            };
            
            activityLog.unshift(logItem);
            
            // 限制日志数量
            if (activityLog.length > MAX_LOG_ITEMS) {
                activityLog.pop();
            }
            
            updateActivityLogDisplay();
        }

        // 更新活动日志显示
        function updateActivityLogDisplay() {
            const logContainer = document.getElementById('activity-log');
            logContainer.innerHTML = '';
            
            activityLog.forEach(item => {
                const logElement = document.createElement('div');
                logElement.className = 'log-item';
                
                const userSpan = document.createElement('span');
                userSpan.className = 'user';
                userSpan.textContent = item.userName;
                
                logElement.appendChild(userSpan);
                logElement.appendChild(document.createTextNode(' ' + item.action));
                
                const timeSpan = document.createElement('div');
                timeSpan.className = 'time';
                timeSpan.textContent = item.time;
                logElement.appendChild(timeSpan);
                
                logContainer.appendChild(logElement);
            });
        }

        // 更新在线用户列表
        function updateOnlineUsersList() {
            const usersList = document.getElementById('users-list');
            usersList.innerHTML = '';
            
            // 添加自己
            const selfItem = createUserItem(userId, userName, ctx.strokeStyle, true);
            usersList.appendChild(selfItem);
            
            // 添加其他用户
            Object.keys(onlineUsers).forEach(id => {
                if (id !== userId) {
                    const user = onlineUsers[id];
                    const userItem = createUserItem(id, user.name, user.color, true);
                    usersList.appendChild(userItem);
                }
            });
        }

        // 创建用户列表项
        function createUserItem(id, name, color, isOnline) {
            const li = document.createElement('li');
            li.className = 'user-item';
            li.dataset.userId = id;
            
            const avatar = document.createElement('div');
            avatar.className = 'user-avatar' + (isOnline ? ' online' : '');
            avatar.style.backgroundColor = color;
            
            // 添加用户首字母或图标
            const initial = document.createElement('span');
            initial.textContent = name.charAt(0).toUpperCase();
            initial.style.color = getContrastColor(color);
            avatar.appendChild(initial);
            
            const userName = document.createElement('div');
            userName.className = 'user-name';
            userName.textContent = name;
            
            li.appendChild(avatar);
            li.appendChild(userName);
            
            return li;
        }

        // 获取对比色（确保文字在背景上可见）
        function getContrastColor(hexColor) {
            // 移除#号
            if (hexColor.startsWith('#')) {
                hexColor = hexColor.substring(1);
            }
            
            // 转换为RGB
            const r = parseInt(hexColor.substr(0, 2), 16);
            const g = parseInt(hexColor.substr(2, 2), 16);
            const b = parseInt(hexColor.substr(4, 2), 16);
            
            // 计算亮度
            const brightness = (r * 299 + g * 587 + b * 114) / 1000;
            
            // 亮度大于128返回黑色，否则返回白色
            return brightness > 128 ? '#000000' : '#ffffff';
        }

        // WebSocket 连接
        var ws = null;
        var wsReconnectAttempts = 0;
        var wsReconnectMaxAttempts = 5;
        var wsReconnectTimeout = null;

        function connectWebSocket() {
            try {
                ws = new WebSocket('ws://39.101.68.140:39005');
                
                // WebSocket 连接建立时
                ws.onopen = function () {
                    console.log('WebSocket连接已建立');
                    wsReconnectAttempts = 0; // 重置重连计数
                    
                    // 发送用户加入消息
                    sendOperation({
                        type: 'userJoined',
                        color: ctx.strokeStyle
                    });
                    
                    // 请求历史记录
                    ws.send(JSON.stringify({type: 'requestHistory'}));
                    
                    // 如果有保存的背景颜色，发送给服务器
                    const savedBackground = localStorage.getItem('drawBackground');
                    if (savedBackground) {
                        sendOperation({type: 'setBackground', color: savedBackground});
                    }
                    
                    // 添加自己的加入日志
                    addActivityLog(userId, userName, '加入了绘画');
                };
                
                // WebSocket 消息处理
                ws.onmessage = function (e) {
                    var data = JSON.parse(e.data);
                    
                    // 如果是其他用户的光标移动
                    if (data.type === 'cursorMove' && data.userId !== userId) {
                        updateUserCursor(data.userId, data.userName, data.relX, data.relY, data.color);
                        
                        // 更新在线用户列表
                        if (!onlineUsers[data.userId]) {
                            onlineUsers[data.userId] = {
                                name: data.userName,
                                color: data.color,
                                lastX: data.relX * CANVAS_WIDTH,
                                lastY: data.relY * CANVAS_HEIGHT
                            };
                            updateOnlineUsersList();
                            addActivityLog(data.userId, data.userName, '加入了绘画');
                        } else {
                            onlineUsers[data.userId].lastX = data.relX * CANVAS_WIDTH;
                            onlineUsers[data.userId].lastY = data.relY * CANVAS_HEIGHT;
                        }
                        return;
                    }
                    
                    // 如果是其他用户的绘画操作
                    if ((data.type === 1 || data.type === 2) && data.userId !== userId) {
                        sharedCtx.strokeStyle = data.color;
                        sharedCtx.lineWidth = data.size;
                        // 设置混合模式
                        sharedCtx.globalCompositeOperation = data.blendMode || 'source-over';
                        
                        // 转换相对坐标为绝对坐标
                        const absCoords = convertToAbsoluteCoordinates(data.relX, data.relY);
                        
                        if (data.type === 1) {
                            sharedCtx.beginPath();
                            sharedCtx.moveTo(absCoords.x, absCoords.y);
                            
                            // 保存该用户的最后一个点位置
                            if (!onlineUsers[data.userId]) {
                                onlineUsers[data.userId] = {
                                    name: data.userName,
                                    color: data.color
                                };
                            }
                            onlineUsers[data.userId].lastX = absCoords.x;
                            onlineUsers[data.userId].lastY = absCoords.y;
                        } else if (data.type === 2) {
                            // 获取该用户上一个点的绝对坐标
                            const lastAbsX = onlineUsers[data.userId] ? onlineUsers[data.userId].lastX : 0;
                            const lastAbsY = onlineUsers[data.userId] ? onlineUsers[data.userId].lastY : 0;
                            
                            // 如果有中点坐标，使用贝塞尔曲线
                            if (data.relMidX && data.relMidY) {
                                const absMidCoords = convertToAbsoluteCoordinates(data.relMidX, data.relMidY);
                                
                                sharedCtx.beginPath();
                                sharedCtx.moveTo(lastAbsX, lastAbsY);
                                sharedCtx.quadraticCurveTo(absMidCoords.x, absMidCoords.y, absCoords.x, absCoords.y);
                                sharedCtx.stroke();
                            } else {
                                sharedCtx.beginPath();
                                sharedCtx.moveTo(lastAbsX, lastAbsY);
                                sharedCtx.lineTo(absCoords.x, absCoords.y);
                                sharedCtx.stroke();
                            }
                            
                            // 更新该用户的最后一个点位置
                            if (!onlineUsers[data.userId]) {
                                onlineUsers[data.userId] = {
                                    name: data.userName,
                                    color: data.color
                                };
                            }
                            onlineUsers[data.userId].lastX = absCoords.x;
                            onlineUsers[data.userId].lastY = absCoords.y;
                        }
                        
                        // 更新主画布显示
                        ctx.clearRect(0, 0, el.width, el.height);
                        ctx.drawImage(sharedCanvas, 0, 0);
                        
                        // 如果有个人绘画，再叠加上去
                        if (currentStep >= 0) {
                            ctx.putImageData(history[currentStep], 0, 0);
                        }
                        
                        return;
                    }
                    
                    // 处理其他操作
                    switch (data.type) {
                        case 'history':
                            // 接收历史记录
                            if (data.image) {
                                const img = new Image();
                                img.onload = function() {
                                    sharedCtx.clearRect(0, 0, sharedCanvas.width, sharedCanvas.height);
                                    sharedCtx.drawImage(img, 0, 0);
                                    ctx.clearRect(0, 0, el.width, el.height);
                                    ctx.drawImage(sharedCanvas, 0, 0);
                                    
                                    // 如果有个人历史记录，叠加上去
                                    if (currentStep >= 0) {
                                        ctx.putImageData(history[currentStep], 0, 0);
                                    }
                                };
                                img.src = data.image;
                            }
                            break;
                            
                        case 'userJoined':
                            // 新用户加入
                            onlineUsers[data.userId] = {
                                name: data.userName,
                                color: data.color || '#000000'
                            };
                            updateOnlineUsersList();
                            addActivityLog(data.userId, data.userName, '加入了绘画');
                            
                            // 向新用户发送当前画布状态
                            if (data.userId !== userId) {
                                const sharedImage = sharedCanvas.toDataURL();
                                sendOperation({
                                    type: 'canvasState',
                                    targetUserId: data.userId,
                                    image: sharedImage
                                });
                            }
                            break;
                            
                        case 'userLeft':
                            // 用户离开
                            if (userCursors[data.userId]) {
                                document.body.removeChild(userCursors[data.userId]);
                                delete userCursors[data.userId];
                            }
                            
                            if (onlineUsers[data.userId]) {
                                addActivityLog(data.userId, onlineUsers[data.userId].name, '离开了绘画');
                                delete onlineUsers[data.userId];
                                updateOnlineUsersList();
                            }
                            break;
                            
                        case 'canvasState':
                            // 接收画布状态（仅针对新加入的用户）
                            if (data.targetUserId === userId) {
                                const img = new Image();
                                img.onload = function() {
                                    sharedCtx.drawImage(img, 0, 0);
                                    ctx.drawImage(sharedCanvas, 0, 0);
                                };
                                img.src = data.image;
                            }
                            break;
                            
                        case 'setColor':
                            // 同步颜色设置（仅更新UI，不影响自己的绘画）
                            if (data.userId !== userId) {
                                if (userCursors[data.userId]) {
                                    userCursors[data.userId].style.backgroundColor = data.color;
                                }
                                if (onlineUsers[data.userId]) {
                                    onlineUsers[data.userId].color = data.color;
                                    updateOnlineUsersList();
                                    addActivityLog(data.userId, onlineUsers[data.userId].name, '更改了画笔颜色');
                                }
                            }
                            break;
                            
                        case 'setBackground':
                            // 应用背景颜色
                            document.getElementById('background').value = data.color;
                            document.body.style.backgroundColor = data.color;
                            if (data.userId !== userId && onlineUsers[data.userId]) {
                                addActivityLog(data.userId, onlineUsers[data.userId].name, '更改了背景颜色');
                            }
                            break;
                            
                        case 'clear':
                            // 清空共享画布（但不影响个人画布）
                            if (data.userId !== userId) {
                                sharedCtx.clearRect(0, 0, sharedCanvas.width, sharedCanvas.height);
                                ctx.clearRect(0, 0, el.width, el.height);
                                ctx.drawImage(sharedCanvas, 0, 0);
                                
                                // 如果有个人绘画，再叠加上去
                                if (currentStep >= 0) {
                                    ctx.putImageData(history[currentStep], 0, 0);
                                }
                                
                                if (onlineUsers[data.userId]) {
                                    addActivityLog(data.userId, onlineUsers[data.userId].name, '清空了画布');
                                }
                            }
                            break;
                            
                        case 'setBlendMode':
                            // 同步混合模式设置
                            if (data.userId !== userId) {
                                if (onlineUsers[data.userId]) {
                                    onlineUsers[data.userId].blendMode = data.blendMode;
                                    addActivityLog(data.userId, onlineUsers[data.userId].name, '更改了混合模式为 ' + getBlendModeName(data.blendMode));
                                }
                            }
                            break;
                    }
                };
                
                // WebSocket 关闭时
                ws.onclose = function(e) {
                    console.log('WebSocket连接已关闭:', e.code, e.reason);
                    
                    // 尝试重新连接
                    if (wsReconnectAttempts < wsReconnectMaxAttempts) {
                        wsReconnectAttempts++;
                        console.log(`尝试重新连接... (${wsReconnectAttempts}/${wsReconnectMaxAttempts})`);
                        
                        if (wsReconnectTimeout) {
                            clearTimeout(wsReconnectTimeout);
                        }
                        
                        // 指数退避重连
                        const reconnectDelay = Math.min(1000 * Math.pow(2, wsReconnectAttempts), 30000);
                        wsReconnectTimeout = setTimeout(connectWebSocket, reconnectDelay);
                    } else {
                        // 使用统一的错误提示
                        if (window.toast && window.toast.error) {
                            window.toast.error('连接已断开，请刷新页面重新连接');
                        } else if (window.showError) {
                            window.showError('连接已断开，请刷新页面重新连接');
                        } else {
                            console.error('连接已断开，请刷新页面重新连接');
                        }
                    }
                };
                
                // WebSocket 错误处理
                ws.onerror = function(err) {
                    console.error('WebSocket错误:', err);
                };
            } catch (e) {
                console.error('WebSocket连接失败:', e);
            }
        }

        // 初始化WebSocket连接
        connectWebSocket();

        // 处理触摸和鼠标事件
        function handleStart(e) {
            isDrawing = true;
            
            // 获取正确的坐标
            const coords = getCoordinates(e);
            
            // 转换为画布坐标系
            const canvasCoords = convertToCanvasCoordinates(coords.x, coords.y);
            lastX = canvasCoords.x;
            lastY = canvasCoords.y;
            
            ctx.beginPath();
            ctx.moveTo(lastX, lastY);
            
            // 发送相对坐标（百分比）
            const relativeCoords = convertToRelativeCoordinates(lastX, lastY);
            sendPoint({
                relX: relativeCoords.x, 
                relY: relativeCoords.y, 
                type: 1, 
                blendMode: ctx.globalCompositeOperation
            });
            
            // 发送光标位置
            sendCursorPosition(lastX, lastY);
            
            e.preventDefault();
        }

        function handleMove(e) {
            // 获取正确的坐标
            const coords = getCoordinates(e);
            
            // 转换为画布坐标系
            const canvasCoords = convertToCanvasCoordinates(coords.x, coords.y);
            const x = canvasCoords.x;
            const y = canvasCoords.y;
            
            // 发送光标位置，无论是否在绘制
            sendCursorPosition(x, y);
            
            if (!isDrawing) return;
            
            // 使用二次贝塞尔曲线使线条更流畅
            ctx.beginPath();
            ctx.moveTo(lastX, lastY);
            
            // 计算控制点
            const midX = (lastX + x) / 2;
            const midY = (lastY + y) / 2;
            
            ctx.quadraticCurveTo(midX, midY, x, y);
            ctx.stroke();
            
            // 同时在共享画布上绘制
            sharedCtx.strokeStyle = ctx.strokeStyle;
            sharedCtx.lineWidth = ctx.lineWidth;
            sharedCtx.globalCompositeOperation = ctx.globalCompositeOperation;
            sharedCtx.beginPath();
            sharedCtx.moveTo(lastX, lastY);
            sharedCtx.quadraticCurveTo(midX, midY, x, y);
            sharedCtx.stroke();
            
            // 发送相对坐标（百分比）
            const relativeCoords = convertToRelativeCoordinates(x, y);
            const relativeMidCoords = convertToRelativeCoordinates(midX, midY);
            sendPoint({
                relX: relativeCoords.x, 
                relY: relativeCoords.y, 
                relMidX: relativeMidCoords.x, 
                relMidY: relativeMidCoords.y, 
                type: 2,
                blendMode: ctx.globalCompositeOperation
            });
            
            lastX = x;
            lastY = y;
            
            e.preventDefault();
        }

        function handleEnd(e) {
            if (!isDrawing) return;
            isDrawing = false;
            saveStep();
            e.preventDefault();
        }

        // 获取坐标的辅助函数
        function getCoordinates(e) {
            let x, y;
            
            if (e.type.includes('touch')) {
                x = e.touches[0].clientX;
                y = e.touches[0].clientY;
            } else {
                x = e.clientX;
                y = e.clientY;
            }
            
            return {x, y};
        }

        // 将页面坐标转换为画布坐标
        function convertToCanvasCoordinates(pageX, pageY) {
            const rect = el.getBoundingClientRect();
            return {
                x: (pageX - rect.left) * (el.width / rect.width),
                y: (pageY - rect.top) * (el.height / rect.height)
            };
        }

        // 将绝对坐标转换为相对坐标（百分比）
        function convertToRelativeCoordinates(x, y) {
            return {
                x: x / CANVAS_WIDTH,
                y: y / CANVAS_HEIGHT
            };
        }

        // 将相对坐标转换为绝对坐标
        function convertToAbsoluteCoordinates(relX, relY) {
            return {
                x: relX * CANVAS_WIDTH,
                y: relY * CANVAS_HEIGHT
            };
        }

        // 保存当前步骤（仅保存个人绘画历史）
        function saveStep() {
            if (currentStep < history.length - 1) {
                history.splice(currentStep + 1);
            }
            const imageData = ctx.getImageData(0, 0, el.width, el.height);
            history.push(imageData);
            currentStep++;
            saveHistoryToStorage();
            sendOperation({type: 'saveStep', userId: userId});
        }

        // 添加事件监听器
        el.addEventListener('mousedown', handleStart);
        el.addEventListener('mousemove', handleMove);
        el.addEventListener('mouseup', handleEnd);
        el.addEventListener('mouseout', handleEnd);

        // 触摸事件
        el.addEventListener('touchstart', handleStart);
        el.addEventListener('touchmove', handleMove);
        el.addEventListener('touchend', handleEnd);
        el.addEventListener('touchcancel', handleEnd);

        // 发送点数据到 WebSocket
        function sendPoint(data) {
            if (!ws || ws.readyState !== WebSocket.OPEN) {
                console.log('WebSocket未连接，无法发送数据');
                return;
            }
            
            try {
                data.color = ctx.strokeStyle;
                data.size = ctx.lineWidth;
                data.userId = userId;
                data.userName = userName;
                ws.send(JSON.stringify(data));
            } catch (e) {
                console.error('发送点数据失败:', e);
            }
        }

        // 发送操作数据到 WebSocket
        function sendOperation(data) {
            if (!ws || ws.readyState !== WebSocket.OPEN) {
                console.log('WebSocket未连接，无法发送数据');
                return;
            }
            
            try {
                data.userId = userId;
                data.userName = userName;
                ws.send(JSON.stringify(data));
            } catch (e) {
                console.error('发送操作数据失败:', e);
            }
        }

        // 发送光标位置
        function sendCursorPosition(x, y) {
            if (!ws || ws.readyState !== WebSocket.OPEN) {
                return;
            }
            
            try {
                // 发送相对坐标
                const relativeCoords = convertToRelativeCoordinates(x, y);
                ws.send(JSON.stringify({
                    type: 'cursorMove',
                    relX: relativeCoords.x,
                    relY: relativeCoords.y,
                    userId: userId,
                    userName: userName,
                    color: ctx.strokeStyle
                }));
            } catch (e) {
                console.error('发送光标位置失败:', e);
            }
        }

        // 创建或更新用户光标
        function updateUserCursor(userId, userName, relX, relY, color) {
            if (userId === window.userId) return; // 不显示自己的光标
            
            // 转换为当前设备的绝对坐标
            const absCoords = convertToAbsoluteCoordinates(relX, relY);
            
            let cursor = userCursors[userId];
            if (!cursor) {
                cursor = document.createElement('div');
                cursor.className = 'user-cursor';
                cursor.dataset.user = userName;
                document.body.appendChild(cursor);
                userCursors[userId] = cursor;
            }
            
            // 获取画布在页面中的位置
            const rect = el.getBoundingClientRect();
            const cursorX = (absCoords.x / CANVAS_WIDTH) * rect.width + rect.left;
            const cursorY = (absCoords.y / CANVAS_HEIGHT) * rect.height + rect.top;
            
            cursor.style.left = cursorX + 'px';
            cursor.style.top = cursorY + 'px';
            cursor.style.backgroundColor = color;
        }
        
        // 获取混合模式的中文名称
        function getBlendModeName(blendMode) {
            const blendModes = {
                'source-over': '正常',
                'multiply': '正片叠底',
                'screen': '滤色',
                'overlay': '叠加',
                'darken': '变暗',
                'lighten': '变亮',
                'color-dodge': '颜色减淡',
                'color-burn': '颜色加深',
                'hard-light': '强光',
                'soft-light': '柔光',
                'difference': '差值',
                'exclusion': '排除',
                'hue': '色相',
                'saturation': '饱和度',
                'color': '颜色',
                'luminosity': '亮度'
            };
            
            return blendModes[blendMode] || blendMode;
        }

        // 控制栏操作
        document.getElementById('color').addEventListener('change', function () {
            ctx.strokeStyle = this.value;
            updateActiveColor(this.value);
            sendOperation({type: 'setColor', color: this.value});
            addActivityLog(userId, userName, '更改了画笔颜色');
        });

        document.getElementById('size').addEventListener('input', function () {
            ctx.lineWidth = this.value;
            document.getElementById('sizeValue').textContent = this.value;
            sendOperation({type: 'setSize', size: this.value});
        });

        document.getElementById('blend-mode').addEventListener('change', function() {
            ctx.globalCompositeOperation = this.value;
            sendOperation({type: 'setBlendMode', blendMode: this.value});
            addActivityLog(userId, userName, '更改了混合模式为 ' + getBlendModeName(this.value));
        });

        document.getElementById('background').addEventListener('change', function () {
            // 更改背景色
            document.body.style.backgroundColor = this.value;
            saveBackgroundToStorage(this.value);
            
            // 保存步骤并同步
            sendOperation({type: 'setBackground', color: this.value});
            addActivityLog(userId, userName, '更改了背景颜色');
        });

        document.getElementById('clear').addEventListener('click', function () {
            // 清空个人画布
            ctx.clearRect(0, 0, el.width, el.height);
            history = [];
            currentStep = -1;
            saveHistoryToStorage();
            
            // 清空共享画布
            sharedCtx.clearRect(0, 0, sharedCanvas.width, sharedCanvas.height);
            
            sendOperation({type: 'clear'});
            addActivityLog(userId, userName, '清空了画布');
        });

        document.getElementById('undo').addEventListener('click', function () {
            // 只能撤销自己的绘画
            if (currentStep > 0) {
                currentStep--;
                
                // 重绘：先绘制共享画布，再绘制个人历史
                ctx.clearRect(0, 0, el.width, el.height);
                ctx.drawImage(sharedCanvas, 0, 0);
                if (currentStep >= 0) {
                    ctx.putImageData(history[currentStep], 0, 0);
                }
                
                saveHistoryToStorage();
                sendOperation({type: 'undo'});
            }
        });

        document.getElementById('redo').addEventListener('click', function () {
            // 只能重做自己的绘画
            if (currentStep < history.length - 1) {
                currentStep++;
                
                // 重绘：先绘制共享画布，再绘制个人历史
                ctx.clearRect(0, 0, el.width, el.height);
                ctx.drawImage(sharedCanvas, 0, 0);
                ctx.putImageData(history[currentStep], 0, 0);
                
                saveHistoryToStorage();
                sendOperation({type: 'redo'});
            }
        });

        // 防止页面滑动
        document.addEventListener('touchmove', function(e) {
            if (e.target === el) {
                e.preventDefault();
            }
        }, { passive: false });
        
        // 设置全局用户ID
        window.userId = userId;

        // 窗口大小调整时重设画布容器
        let resizeTimeout = null;
        window.addEventListener('resize', function() {
            // 防抖，避免频繁调整大小导致性能问题
            if (resizeTimeout) {
                clearTimeout(resizeTimeout);
            }
            
            resizeTimeout = setTimeout(function() {
                adjustCanvasContainer();
                
                // 更新在线用户的光标位置
                for (const userId in userCursors) {
                    if (onlineUsers[userId]) {
                        const absCoords = convertToAbsoluteCoordinates(
                            onlineUsers[userId].lastX / CANVAS_WIDTH, 
                            onlineUsers[userId].lastY / CANVAS_HEIGHT
                        );
                        
                        // 更新光标位置
                        const rect = el.getBoundingClientRect();
                        const cursorX = (absCoords.x / CANVAS_WIDTH) * rect.width + rect.left;
                        const cursorY = (absCoords.y / CANVAS_HEIGHT) * rect.height + rect.top;
                        
                        userCursors[userId].style.left = cursorX + 'px';
                        userCursors[userId].style.top = cursorY + 'px';
                    }
                }
            }, 300); // 300ms防抖
        });
    </script>
</body>
</html>